//@ts-nocheck
import React, { useEffect, useImperativeHandle } from 'react'

import * as echarts from 'echarts/lib/echarts'
import 'echarts/lib/component/legend'
import 'echarts/lib/chart/pie'

import { PieItem } from './interface'
import './index.less'
import { ChartsInstance } from '../Bar/interface'

let echartsInstance: any

interface IProps {
  chartId?: string
  data: Array<PieItem>
  chartRef?: React.MutableRefObject<ChartsInstance>
}

const PieChart: React.FC<IProps> = ({ chartId, chartRef, data = [] }) => {
  useEffect(() => {
    echartsInstance = echarts.init(document.getElementById(chartId || 'charts-pie-chart'))
    // setOptions()
  }, [])

  useEffect(() => {
    if (echartsInstance) setOptions()
  }, [data])

  useImperativeHandle(chartRef, () => ({
    getInstance: () => {
      return echartsInstance
    }
  }))

  const setOptions = () => {
    echartsInstance.setOption({
      tooltip: {
        trigger: 'item',
        formatter: '{b} : {c} ({d}%)'
      },
      grid: {
        left: '5%',
        top: 0,
        bottom: 0,
        right: '5%'
      },
      legend: {
        // orient: 'vertical',
        bottom: 0
      },
      series: [
        {
          type: 'pie',
          radius: data.length > 20 ? '50%' : '60%',
          bottom: data.length > 20 ? 40 : 30,
          top: 0,
          data,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }
      ]
    })
  }

  return <div className="charts-pie-chart" id={chartId || 'charts-pie-chart'} />
}
export default (PieChart)
